from fastapi import APIRouter, HTTPException, Depends
from typing import List, Dict, Any

from dto.universal_request import (
    UniversalVideoRequest,
    UniversalVideoInfoRequest
)
from dto.universal_response import (
    UniversalVideoDownloadResponse,
    UniversalVideoInfoResponse,
    UniversalMultiQualityResponse,
    UniversalSupportedPlatformsResponse,
    VideoPlatform
)
from service.universal_downloader_service import UniversalDownloaderService
from config.logging_config import ProjectLoggers

logger = ProjectLoggers.get_service_logger()

# 创建路由器
router = APIRouter(prefix="/universal", tags=["Universal Video Downloader"])

# 创建服务实例
universal_service = UniversalDownloaderService()


@router.post("/download-url", response_model=UniversalVideoDownloadResponse)
async def get_universal_download_url(request: UniversalVideoRequest):
    """
    通用视频下载接口 - 自动识别平台并获取下载链接
    
    支持的平台：
    - Facebook: facebook.com/watch, fb.watch
    - Instagram: instagram.com/p, instagram.com/reel  
    - Twitter/X: twitter.com/status, x.com/status
    - YouTube: youtube.com, youtu.be
    
    Args:
        request: 通用视频请求对象（包含URL和质量选项）
        
    Returns:
        统一格式的视频下载信息，包含自动识别的平台信息
    """
    try:
        logger.info(f"通用下载链接请求: {request.url}, 质量: {request.quality}")
        
        result = await universal_service.get_download_url(request.url, request.quality)
        
        if result["success"]:
            return UniversalVideoDownloadResponse(
                success=True,
                platform=result["platform"],
                data=result["data"]
            )
        else:
            return UniversalVideoDownloadResponse(
                success=False,
                platform=result.get("platform"),
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"通用下载链接请求异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.post("/quick-url", response_model=UniversalVideoDownloadResponse)
async def get_universal_quick_url(request: UniversalVideoInfoRequest):
    """
    快速获取视频下载链接（最佳质量）- 自动识别平台
    
    Args:
        request: 通用视频信息请求对象
        
    Returns:
        最佳质量的视频下载链接
    """
    try:
        logger.info(f"通用快速下载链接请求: {request.url}")
        
        result = await universal_service.get_download_url(request.url, "best")
        
        if result["success"]:
            return UniversalVideoDownloadResponse(
                success=True,
                platform=result["platform"],
                data=result["data"]
            )
        else:
            return UniversalVideoDownloadResponse(
                success=False,
                platform=result.get("platform"),
                error=result["error"]
            )
            
    except Exception as e:
        logger.error(f"通用快速下载链接请求异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.get("/supported-platforms", response_model=UniversalSupportedPlatformsResponse)
async def get_supported_platforms():
    """
    获取支持的视频平台列表
    
    Returns:
        支持的平台列表和详细信息
    """
    try:
        platforms = [
            {
                "platform": "facebook",
                "name": "Facebook",
                "description": "Facebook视频和Reels",
                "supported_urls": [
                    "https://www.facebook.com/watch/",
                    "https://www.facebook.com/videos/",
                    "https://www.facebook.com/posts/",
                    "https://fb.watch/"
                ],
                "features": ["视频下载", "质量选择", "视频信息获取", "多质量链接"]
            },
            {
                "platform": "instagram",
                "name": "Instagram",
                "description": "Instagram帖子、Reels和IGTV",
                "supported_urls": [
                    "https://www.instagram.com/p/",
                    "https://www.instagram.com/reel/",
                    "https://www.instagram.com/tv/"
                ],
                "features": ["媒体下载", "质量选择", "用户媒体", "社交数据"]
            },
            {
                "platform": "twitter",
                "name": "Twitter/X",
                "description": "Twitter/X推文视频",
                "supported_urls": [
                    "https://twitter.com/username/status/",
                    "https://x.com/username/status/",
                    "https://mobile.twitter.com/username/status/"
                ],
                "features": ["视频下载", "质量选择", "推文信息", "社交数据"]
            },
            {
                "platform": "youtube",
                "name": "YouTube",
                "description": "YouTube视频",
                "supported_urls": [
                    "https://www.youtube.com/watch?v=",
                    "https://youtu.be/",
                    "https://m.youtube.com/watch?v="
                ],
                "features": ["视频下载", "质量选择", "视频信息", "多格式支持"]
            }
        ]
        
        description = (
            "通用视频下载器支持多个主流社交媒体平台：\n\n"
            "🎯 自动平台识别 - 无需手动选择平台\n"
            "📱 多平台支持 - Facebook、Instagram、Twitter/X、YouTube\n"
            "🎬 多种质量 - 支持不同分辨率选择\n"
            "📊 详细信息 - 获取视频元数据和社交数据\n"
            "⚡ 高性能 - 异步处理，快速响应\n\n"
            "使用方法：直接提供任何支持平台的视频链接，"
            "系统将自动识别平台并返回统一格式的结果。"
        )
        
        return UniversalSupportedPlatformsResponse(
            success=True,
            platforms=platforms,
            total_platforms=len(platforms),
            description=description
        )
        
    except Exception as e:
        logger.error(f"获取支持平台列表异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}")


@router.post("/detect-platform")
async def detect_video_platform(request: UniversalVideoInfoRequest):
    """
    检测视频链接所属平台（仅检测，不下载）
    
    Args:
        request: 通用视频信息请求对象
        
    Returns:
        检测到的平台信息
    """
    try:
        logger.info(f"平台检测请求: {request.url}")
        
        platform = universal_service.detect_platform(request.url)
        
        platform_info = {
            "url": request.url,
            "detected_platform": platform.value,
            "is_supported": platform != VideoPlatform.UNKNOWN,
            "platform_description": {
                VideoPlatform.FACEBOOK: "Facebook - 支持Watch、Videos、Posts、Reels",
                VideoPlatform.INSTAGRAM: "Instagram - 支持Posts、Reels、IGTV",
                VideoPlatform.TWITTER: "Twitter/X - 支持推文视频",
                VideoPlatform.YOUTUBE: "YouTube - 支持所有公开视频",
                VideoPlatform.UNKNOWN: "未知平台 - 不支持的链接格式"
            }.get(platform, "未知平台")
        }
        
        return {
            "success": True,
            "data": platform_info
        }
        
    except Exception as e:
        logger.error(f"平台检测异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"服务异常: {str(e)}") 